package org.jradweb.core.taglib;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyContent;

import org.jradweb.core.controller.JMultiActionController;
import org.springframework.beans.BeansException;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public class LinkTag extends BaseTag{

	private String controller;
	private String action;
	private Object oid;
	
	public Object getOid() {
		return oid;
	}
	public void setOid(Object oid) {
		this.oid = oid;
	}
	public String getAction() {
		return action;
	}
	public void setAction(String action) {
		this.action = action;
	}
	public String getController() {
		return controller;
	}
	public void setController(String controller) {
		this.controller = controller;
	}
	@Override
	public int doEndTag() throws JspException {
		HttpServletRequest req=(HttpServletRequest)pageContext.getRequest();
		String contextPath=req.getContextPath();
		StringBuffer sb=new StringBuffer("<a href=\"").append(contextPath).append("/");
		BodyContent bc=this.getBodyContent();
		try {
			
			Map<String,JMultiActionController> controllers=this.appCtx.getBeansOfType(JMultiActionController.class);
			for(String name:controllers.keySet()){
				JMultiActionController mac=controllers.get(name);
				if(mac.getName()!=null&&mac.getName().equalsIgnoreCase(controller)){
					sb.append(controller.toLowerCase()).append("/");
					if(action!=null)
					{
						sb.append(action).append(".html");
					}
					else{
						sb.append("index.html");
					}
					if(oid!=null){
						sb.append("?id=").append(oid.toString());
					}
					
				}
			}
			sb.append("\">");
			if(bc!=null){
				sb.append(bc.getString());
			}
			sb.append("</a>");
			this.pageContext.getOut().write(sb.toString());
			return super.doEndTag();
		} catch (BeansException e) {
			throw new JspException(e);
		} catch (IOException e) {
			throw new JspException(e);
		}
	}

}
